﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DomainInfoLib;
using System.Threading;
using System.IO;

namespace DomainInfoDigger
{
    public partial class FrmBatchSearch : Form
    {
        public FrmBatchSearch()
        {
            InitializeComponent();
        }

        QueryGroup _QueryGroup = new QueryGroup();
        
        Digger digger;

        EstimateLib.EstimateServer estimater = new EstimateLib.EstimateServer();

        private event EventHandler DigCompleted;

        TimeCost _TimeCost = new TimeCost();

        private void FrmBatchSearch_Load(object sender, EventArgs e)
        {
            DigCompleted += new EventHandler(digger_DigCompleted);

            digger = new Digger();

            digger.DoneOne += new GottenRegisteInfoHandle(digger_DoneOne);


        }

        void digger_DoneOne(QueryItem item)
        {

            if (this.InvokeRequired)
            {
                GottenRegisteInfoHandle _myInvoke = new GottenRegisteInfoHandle(GetARegisterInfo);
                this.Invoke(_myInvoke, item);
            }
            else
            {
                GetARegisterInfo(item);
            }


        }

        void GetARegisterInfo(QueryItem item)
        {
            progressBar1.Value++;

            label2.Text = progressBar1.Value.ToString() + "/" + progressBar1.Maximum.ToString();

            CaculateTimeCost();

            if (progressBar1.Value >= progressBar1.Maximum) digger_DigCompleted(null, null);


            if (IsJustAvaliable() && item.Avaliable() == false) return;

            ListViewItem viewItem = BuildListViewItem(item);

            listView_RegisteInfo.Items.Add(viewItem);
        }

        private void CaculateTimeCost()
        {
            label_PerItemTimeCost.Text = "TimeCost per Item:" + _TimeCost.GetPerTimeCost();
            
            label_RemainTime.Text = "Remain Time:" + _TimeCost.GetRemainTime();
        }

        private bool IsJustAvaliable()
        {
            return !checkBox_UnavaliableIsVisable.Checked;
        }

        private ListViewItem BuildListViewItem(QueryItem item)
        {
            ListViewItem viewItem = new ListViewItem();

            ListViewGroup group = GetGroup(item.KeyWord);

            viewItem.Group = group;

            viewItem.Text = item.DomainFullName;

            viewItem.SubItems.Add(item.Domain); //+ "★☆"

            viewItem.SubItems.Add(item.DomainName);

            viewItem.SubItems.Add(item.Avaliable().HasValue? item.Avaliable().Value.ToString():"无响应");

            viewItem.SubItems.Add(item.GetAPIName());

            viewItem.SubItems.Add(item.GetResponseStr());

            viewItem.ImageKey = "UnKnown";

            
            


            if (item.Avaliable().HasValue && item.Avaliable().Value==true)
            {
                viewItem.ImageKey = "UnRegisted";
                EstimateLib.EstimateResult estimateResult=estimater.Estimate(item.DomainFullName);
                viewItem.SubItems[2].Text = estimateResult.Level + " " + viewItem.SubItems[2].Text;
            }

            if (item.Avaliable().HasValue && item.Avaliable().Value==false)
            {
                viewItem.ImageKey = "Registed";
            }

            return viewItem;
        }

        private ListViewGroup GetGroup(string GroupName)
        {
            if (listView_RegisteInfo.Groups[GroupName] == null)
            {
                listView_RegisteInfo.Groups.Add(GroupName, GroupName);
            }

            return listView_RegisteInfo.Groups[GroupName];
        }

        void digger_DigCompleted(object sender, EventArgs e)
        {
            
            BaseInfo.SaveCache();
            MessageBox.Show("搜索完成");
            
        }

        internal void SetQueryGroup(QueryGroup queryGroup)
        {
            _QueryGroup = queryGroup;
            
            IList<string> list = _QueryGroup.GetStrList();

            uC_ListBox_QueryGroup.SetList(list);

            textBox_QueryGroupInfo.Text = "查询项总数：" + _QueryGroup.Count;

            textBox_QueryGroupInfo.Text += "\r\n预计耗时:\r\n" + _TimeCost.CaculateTimeCost(_QueryGroup.Count);

        }

        private void PrepareSearch()
        {
            listView_RegisteInfo.Items.Clear();

            progressBar1.Visible = true;

            progressBar1.Value = 0;

            progressBar1.Maximum = _QueryGroup.Count;

            label1.Text= "搜索中";
            
            label2.Text = progressBar1.Value.ToString() + "/" + progressBar1.Maximum.ToString();

            _TimeCost.Start(_QueryGroup.Count);
        }

        private void button_DoSearch_Click(object sender, EventArgs e)
        {
            PrepareSearch();

            digger.SetThreadCount(GetThreadCount());

            digger.dig(_QueryGroup);
        }

        private int GetThreadCount()
        {
            return int.Parse(textBox_ThreadCount.Text.Trim());
        }

        private void button_Cancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (digger.Cancel())
                {
                    BaseInfo.SaveCache();
                    MessageBox.Show("搜索已中止");
                    label1.Text = "搜索中止";
                    
                }
                    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button_Export_Click(object sender, EventArgs e)
        {
            string saveFileName = GetSaveFileName();

            if (string.IsNullOrEmpty(saveFileName))
            {
                return;
            }

            SaveTxtFile(saveFileName);

        }

        private string GetSaveFileName()
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                return saveFileDialog1.FileName;
            }
            return null;
        }

        public void SaveTxtFile(string path)
        {

            try
            {
                StreamWriter streamw = File.CreateText(path);

                for (int i = 0; i < listView_RegisteInfo.Items.Count; i++)
                {
                    if (listView_RegisteInfo.Items[i] != null)
                    {
                        string text = listView_RegisteInfo.Items[i].Text;

                        streamw.WriteLine(text);
                    }
                }

                streamw.Close();
                MessageBox.Show("ok");
            }
            catch (IOException ex)
            {

            }
            finally
            {
                
            }
        }



        internal string SearchState()
        {
            string tiptxt = label2.Text;


            return tiptxt;
        }
    }
}
